package com.tianqu.tms.www.car.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsAction;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsDaoException;
import com.tianqu.tms.core.util.DateUtil;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.dto.MemberRentalLocationInfo;
import com.tianqu.tms.entity.Codes;
import com.tianqu.tms.entity.Member;
import com.tianqu.tms.www.car.actionform.CarPendingLiftActionForm;
import com.tianqu.tms.www.car.controller.CarSeniorManagementResultController;
import com.tianqu.tms.www.car.viewhelper.CarPendingLiftViewHelper;
/**
 * 高级管理 - 保存结果Action
 * @author mufeiyu
 *
 */
public class CarSeniorManagementResultAction extends TmsAction {
	// 合同编号添加
	public static String SETIALADD = "serialAdd";
	// 保存成功
	public static String ADDSUCCESS = "addsuccess";
	// button的Flag
	public static String BTNFLAG = "btnFlag";
	
	private Logger logger = Logger.getLogger(CarSeniorManagementResultAction.class);

	@Override
	protected ActionForward doAction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		CarPendingLiftActionForm rentalForm = (CarPendingLiftActionForm) uc.getInputForm();
		CarPendingLiftViewHelper view = (CarPendingLiftViewHelper) uc.getAttribute(TmsConstants.VIEWHELP);
		// 判断按钮点击
		Member member = Member.getInstance();				
		member=member.findMemberInfoByMemId(view.getMemId());
		if (!StringUtil.isNullOrBlank(rentalForm.getRentalAddBtn())) {			
			String serial = rentalForm.getSerial();
			if(!StringUtil.isNullOrBlank(serial)){
				boolean result = false;
				if(!StringUtil.isNullOrBlank(member.getBusinessNo())){
					String[] list= member.getBusinessNo().split(",");
					for(int i=0;i<list.length;i++){
						if(serial.equals(list[i])){
							result = true;
							break;
						}
					}
				}
				if(result){
					setErrorsToRequest(request, TmsConstants.U8018, null); // 当前合同对应的租位已经被其他商户使用，不能重复使用。
					request.setAttribute(TmsConstants.VIEWHELP, view);
					uc.setAttribute(TmsConstants.VIEWHELP, view);
					return mapping.findForward(SETIALADD);
				}
			}
			uc.setAttribute(BTNFLAG, "true");
			
			CarSeniorManagementResultController controller = new CarSeniorManagementResultController();
			controller.execute(uc);
			
			CarPendingLiftViewHelper viewHelper = (CarPendingLiftViewHelper) uc.getAttribute(TmsConstants.VIEWHELP);
			request.setAttribute(TmsConstants.VIEWHELP, viewHelper);
			uc.setAttribute(TmsConstants.VIEWHELP, viewHelper);
			logger.debug(this.getClass().getName() + "#execute was completed.");
			return mapping.findForward(SETIALADD);
		} else{
			// 保存
			uc.setAttribute(BTNFLAG, "false");
//			view.setAnnualTransactionVolume(rentalForm.getAnnualTransactionVolume());
//			view.setCarPortStr(rentalForm.getCarPortStr());
			
			MemberRentalLocationInfo memberRentalLocationInfo = Member.getInstance().findMemberRentalLocationInfoCount(member.getBusinessNo());
			String unusedAnnualTransactionVolume = memberRentalLocationInfo.getUnusedAnnualTransactionVolume();
			String unusedCarPort = memberRentalLocationInfo.getUnusedCarPort();
			
			view.setUnusedAnnualTransactionVolume(StringUtil.getPointBetweenThree(StringUtils.isNotBlank(unusedAnnualTransactionVolume)?Integer.parseInt(unusedAnnualTransactionVolume):0));
			view.setUnusedCarPort(StringUtil.getPointBetweenThree(StringUtils.isNotBlank(unusedCarPort)?Integer.parseInt(unusedCarPort):0));
			view.setFragileStickerFreePort(rentalForm.getFragileStickerFreePort());
			view.setRecommend(rentalForm.getRecommend());
			view.setIdentityRangeList(convertIdentityRangeStr(rentalForm.getIdentityRange()));
			view.setTmpIdentityRangeList(convertIdentityRangeStr(rentalForm.getTmpIdentityRange()));
			
			request.setAttribute(TmsConstants.VIEWHELP, view);
			uc.setAttribute(TmsConstants.VIEWHELP, view);
//			if(StringUtil.isNullOrBlank(rentalForm.getCarPortStr())){
//				String[] param = {"允许库存停放数量"};
//				setErrorsToRequest(request, TmsConstants.U0005, param); // 允许库存停放数量必须填写。
//				return mapping.findForward(SETIALADD);
//			}
//			if(StringUtil.isNullOrBlank(rentalForm.getAnnualTransactionVolume())){
//				String[] param = {"允许库存登记数量"};
//				setErrorsToRequest(request, TmsConstants.U0005, param); // 允许库存登记数量必须填写。				
//				return mapping.findForward(SETIALADD);
//			}
			if(StringUtil.isNullOrBlank(rentalForm.getFragileStickerFreePort())){
				String[] param = {"易碎贴免费数量"};
				setErrorsToRequest(request, TmsConstants.U0005, param); // 易碎贴免费数量必须填写。				
				return mapping.findForward(SETIALADD);
			}
			if(StringUtil.isNullOrBlank(rentalForm.getRecommend())){
				String[] param = {"车源推荐权重"};
				setErrorsToRequest(request, TmsConstants.U0005, param); // 车源推荐权重必须填写。				
				return mapping.findForward(SETIALADD);
			}
			
			if(!StringUtil.isNullOrBlank(rentalForm.getContractTime())){
				if(!DateUtil.isValidDate(rentalForm.getContractTime())){
					String[] param = {"有效结束日期", "YYYYMMDD"};
					setErrorsToRequest(request, TmsConstants.U0018, param); 
					return mapping.findForward(SETIALADD);
				}else{
					SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
					// 当前系统日期
					String nowDateStr = formatDate.format(new Date());
					Date nowDate = formatDate.parse(nowDateStr);
					// 有效结束日期	
					Date endDate = formatDate.parse(rentalForm.getContractTime());
					if (endDate.compareTo(nowDate) > 0) {
						String[] param = {"有效结束日期"};
						setErrorsToRequest(request, TmsConstants.U0020, param); 
						return mapping.findForward(SETIALADD);
					}
				}
			}
			
			String[] identityRange = rentalForm.getIdentityRange();
			String[] tmpIdentityRange = rentalForm.getTmpIdentityRange();
			boolean repeatFlg = false;
			if(null != identityRange && identityRange.length > 0
					&& null != tmpIdentityRange && tmpIdentityRange.length > 0){
				for (int i = 0;i < identityRange.length;i++) {
					for(int j = 0;j < tmpIdentityRange.length;j++) {
						if(identityRange[i].equals(tmpIdentityRange[j])) repeatFlg = true;
					}
				}
				if (repeatFlg) {
					setErrorsToRequest(request, TmsConstants.U8022, null); // 长期有效识别道闸和临时有效识别道闸两个选项不能选择相同道闸编号。				
					return mapping.findForward(SETIALADD);	
				}
			}
			CarSeniorManagementResultController controller = new CarSeniorManagementResultController();
			controller.execute(uc);
			
			CarPendingLiftViewHelper viewHelper = (CarPendingLiftViewHelper) uc.getAttribute(TmsConstants.VIEWHELP);			
			request.setAttribute(TmsConstants.VIEWHELP, viewHelper);
			uc.setAttribute("id", viewHelper.getMemId());
			uc.setAttribute(TmsConstants.VIEWHELP, viewHelper);
		}
		logger.debug(this.getClass().getName() + "#execute was completed.");
		return mapping.findForward(ADDSUCCESS);
	}
	
	private List convertIdentityRangeStr(String[] identityRangeCode) throws TmsDaoException{
		HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
		if(null != identityRangeCode && identityRangeCode.length > 0){
			for (int i = 0; i < identityRangeCode.length; i++){
				int itemCode = StringUtils.isNumeric(identityRangeCode[i])?Integer.parseInt(identityRangeCode[i]):-1;
				map.put(itemCode, itemCode);
			}
		}
		List codeslist = Codes.getInstance().getCodeslistByItemId(Codes.GATEWAY_TYPE);
		for (Object object : codeslist) {
			String checked = "";
			HashMap codesMap = (HashMap)object;
			if(map.get(codesMap.get("itemCode"))!=null ) checked = "checked";
			codesMap.put("checked", checked);
		}
		return codeslist;
	}
}
